package com.hht.tools.uvc

import android.Manifest
import android.graphics.BitmapFactory
import android.graphics.ImageFormat
import android.graphics.Rect
import android.graphics.YuvImage
import android.hardware.usb.UsbDevice
import android.os.Bundle
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import com.herohan.uvcapp.CameraHelper
import com.herohan.uvcapp.ICameraHelper
import com.hht.toolanduilibs.showLog
import com.hht.tools.R
import com.hjq.permissions.XXPermissions
import com.serenegiant.usb.UVCCamera
import com.serenegiant.utils.UsbDeviceHelps
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import java.io.ByteArrayOutputStream
import java.io.IOException


class UvcLibsUI : AppCompatActivity(), ICameraHelper.StateCallback,
    CoroutineScope by MainScope() {
    private lateinit var uvcImageView: ImageView
    private lateinit var mCameraHelper: ICameraHelper
    private var mAutoConnectCamera = true

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.touch_uvc_ui)
        uvcImageView = findViewById(R.id.uvc_image_view)
        mCameraHelper = CameraHelper()
        mCameraHelper.setStateCallback(this)
        "size====${mCameraHelper.deviceList.size}".showLog()
    }

    override fun onResume() {
        super.onResume()
        mCameraHelper.startPreview()

    }

    override fun onPause() {
        super.onPause()
        mCameraHelper.stopPreview()
        mAutoConnectCamera=true
    }

    override fun onDestroy() {
        super.onDestroy()
        mCameraHelper.release()
    }

    private fun onPreviewResult(data: ByteArray) {
        val mTempWidth = mCameraHelper?.previewSize?.width
        val mTempHeight = mCameraHelper?.previewSize?.height
        if (mTempWidth == null || mTempHeight == null || mTempHeight == 0 || mTempWidth == 0) {
            return
        }
        val yuvImage = YuvImage(data, ImageFormat.NV21, mTempWidth, mTempHeight, null)
        val bos = ByteArrayOutputStream(data.size)
        val result = yuvImage.compressToJpeg(Rect(0, 0, mTempWidth, mTempHeight), 80, bos)
        if (result) {
            val buffer = bos.toByteArray()
            val bitmap = BitmapFactory.decodeByteArray(buffer, 0, buffer.size)
            launch {
                uvcImageView.setImageBitmap(bitmap)
            }
        }
        try {
            bos.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }


    private fun selectDevice(device: UsbDevice) {
        // 通过UsbDevice对象，尝试获取设备权限
        XXPermissions.with(this)
            .permission(Manifest.permission.CAMERA)
            .request { permissions, all ->
                "permissions===$permissions, all===$all".showLog()
                if (all) {
                    mCameraHelper.selectDevice(device)
                }
            }
    }


    override fun onAttach(device: UsbDevice?) {
        "onAttach,   device==${device?.deviceName},${device?.productName}".showLog(1)
        if (UsbDeviceHelps.isUsbCameraDevice(device)) {
            device?.let {
                if (mAutoConnectCamera) {
                    mAutoConnectCamera = false
                    selectDevice(device)
                }
            }
        }
    }

    override fun onDeviceOpen(device: UsbDevice?, isFirstOpen: Boolean) {
        "onDeviceOpen,  device==${device?.deviceName},${device?.productName}".showLog(1)
        mCameraHelper.openCamera()
    }

    override fun onCameraOpen(device: UsbDevice?) {
        "onCameraOpen,   device==${device?.deviceName},${device?.productName}".showLog(1)
        mCameraHelper?.startPreview()
        mCameraHelper?.setFrameCallback({ frame ->
            frame?.let {
                val len = it.capacity()
                val yuv = ByteArray(len)
                it.get(yuv)
                onPreviewResult(yuv)
            }
        }, UVCCamera.PIXEL_FORMAT_NV21)
    }

    override fun onCameraClose(device: UsbDevice?) {

    }

    override fun onDeviceClose(device: UsbDevice?) {

    }

    override fun onDetach(device: UsbDevice?) {
        mAutoConnectCamera=true
    }

    override fun onCancel(device: UsbDevice?) {

    }

}